import { useState, useCallback } from 'react'

export interface ImageItem {
  /** 图片ID */
  id: string
  /** 图片地址 */
  src: string
  /** 图片标题 */
  title?: string
  /** 图片描述 */
  alt?: string
}

export interface UseImageGalleryOptions {
  /** 初始索引 */
  initialIndex?: number
  /** 是否循环 */
  loop?: boolean
}

/**
 * useImageGallery Hook
 * 图片画廊预览管理
 */
export const useImageGallery = ({ initialIndex = 0, loop = true }: UseImageGalleryOptions = {}) => {
  const [visible, setVisible] = useState(false)
  const [currentIndex, setCurrentIndex] = useState(initialIndex)
  const [images, setImages] = useState<ImageItem[]>([])

  /**
   * 打开图片预览
   */
  const open = useCallback((imageList: ImageItem[], index: number = 0) => {
    setImages(imageList)
    setCurrentIndex(index)
    setVisible(true)
  }, [])

  /**
   * 关闭图片预览
   */
  const close = useCallback(() => {
    setVisible(false)
  }, [])

  /**
   * 切换显示状态
   */
  const toggle = useCallback(() => {
    setVisible((prev) => !prev)
  }, [])

  /**
   * 下一张
   */
  const next = useCallback(() => {
    setCurrentIndex((prev) => {
      if (prev >= images.length - 1) {
        return loop ? 0 : prev
      }
      return prev + 1
    })
  }, [images.length, loop])

  /**
   * 上一张
   */
  const prev = useCallback(() => {
    setCurrentIndex((prevIndex) => {
      if (prevIndex <= 0) {
        return loop ? images.length - 1 : 0
      }
      return prevIndex - 1
    })
  }, [images.length, loop])

  /**
   * 跳转到指定图片
   */
  const goTo = useCallback((index: number) => {
    if (index >= 0 && index < images.length) {
      setCurrentIndex(index)
    }
  }, [images.length])

  /**
   * 获取当前图片
   */
  const getCurrentImage = useCallback((): ImageItem | null => {
    return images[currentIndex] || null
  }, [images, currentIndex])

  // 派生状态
  const isFirst = currentIndex === 0
  const isLast = currentIndex === images.length - 1
  const canGoPrev = loop || !isFirst
  const canGoNext = loop || !isLast
  const totalCount = images.length

  return {
    // 状态
    visible,
    currentIndex,
    images,
    isFirst,
    isLast,
    canGoPrev,
    canGoNext,
    totalCount,

    // 方法
    open,
    close,
    toggle,
    next,
    prev,
    goTo,
    getCurrentImage,
  }
}

export default useImageGallery

